#include<cstdio>
#include<cstdlib>
#include<unistd.h>
#include<pthread.h>
#include<iostream>

int ticket = 1000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void* Routine(void* args)
{
    char *id =(char*)args;
    while(1)
    {
        pthread_mutex_lock(&lock);
        if(ticket>0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n",id,ticket);
            ticket--;
            pthread_mutex_unlock(&lock);
        }
        else 
        {
            pthread_mutex_unlock(&lock);
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_t t1,t2,t3,t4;

    pthread_create(&t1,nullptr,Routine,(void*)"thread-1");
    pthread_create(&t2,nullptr,Routine,(void*)"thread-2");
    pthread_create(&t3,nullptr,Routine,(void*)"thread-3");
    pthread_create(&t4,nullptr,Routine,(void*)"thread-4");

    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
    pthread_join(t4,nullptr);

    return 0;
}